package cn.itcast.bos.service.impl;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.repository.MenuRepository;
import cn.itcast.bos.repository.PermissionRepository;
import cn.itcast.bos.repository.RoleRepository;
import cn.itcast.bos.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private PermissionRepository permissionRepository;
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Role> findAllRoles(User user) {
		if(user.getUsername()!=null && user.getUsername().equals("admin")){
			// admin具有所有角色
			return roleRepository.findAll();
		}else{
			// 基于用户查询 角色
			return roleRepository.findRolesByUserId(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	/**保存角色*/
	@Override
	public void save(Role role, String[] permissionIds, String menuIds) {
		// 保存角色信息
		roleRepository.save(role);
		// 关联权限
		if(permissionIds != null && permissionIds.length>0){
			for(String permissionId :permissionIds){
				// 查询权限
				Permission permission = permissionRepository.findOne(Integer.parseInt(permissionId));
				role.getPermissions().add(permission);
			}
		}
		// 关联菜单
		if(StringUtils.isNoneBlank(menuIds)){
			String[] menuIdArray = menuIds.split(",");
			for(String menuId : menuIdArray){
				Menu menu = menuRepository.findOne(Integer.parseInt(menuId));
				role.getMenus().add(menu);
			}
		}

	}
}
